package com.example.demo.netty.chat_room.server;

import com.example.demo.netty.chat_room.domain.MessageProtocol;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

public class ServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    // 获取时间
     private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
     // ChannelGroup是用于存放Channel的容器,并且可以对每个内部的channel都执行操作,比如下面的广播
     // 用一个单独的线程去广播信息,而且这个方法生成的线程会再一段时间没任务后自动结束
     private static ChannelGroup channels =new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 组装数据
        String str =ctx.channel().remoteAddress()+"于"+sdf.format(new Date())+"上线";
        byte[] bytes = str.getBytes();
        // 广播出去（会对存储的每个channel都发消息，当前channel除外,毕竟它在下面才添加进来嘛）
        channels.writeAndFlush(new MessageProtocol(bytes.length, bytes));
        System.out.println(str);

        // 将新连接的通道添加进通道容器
        channels.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String str =ctx.channel().remoteAddress()+"于"+sdf.format(new Date())+"下线";
        // 移除对象
        channels.remove(ctx.channel());
        System.out.println(str);
        // 广播下线
        channels.writeAndFlush(str);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol messageProtocol) throws Exception {
        String data= new String(messageProtocol.getData());
        // 断连
        if("断开连接".equals(data)){
            ctx.close();
        }else{
            // 收分好包的数据并用ChannelGroup广播
            Channel channel = ctx.channel();
            String date =sdf.format(new Date())+" ";
            String str ="说："+data;
            for(Channel p: channels){
                String s="";
                if(channel==p){
                    s = date + "你" + str;
                }else{
                    s= date + channel.remoteAddress() + str;
                }
                p.writeAndFlush(new MessageProtocol(s.getBytes().length,s.getBytes()));
//                System.out.println(new MessageProtocol(s.getBytes().length,s.getBytes()));
                System.out.println(s.getBytes().length);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
